<script src="<?php echo base_url();?>js/lib/latlong.js" 		type="text/javascript"></script>
<script type="text/javascript">
/**
 * 
 * @author marcelogdiaz
 * @version 12.5 
 */
 
function addMarker(latitude,longitude, description) {
	var marker = new GMarker(new GLatLng(latitude, longitude));
	GEvent.addListener(marker, 'click',
		function() {
			marker.openInfoWindowHtml(description);
		}
	);
	map.addOverlay(marker);
}

//-------------------------------------------------------
//-------------------------------------------------------
function createMarker(lat, lng, html, iconImage, title) {
	var marker;
	if(iconImage !=''){
		var icon = new GIcon();
		icon.image = iconImage;
		icon.iconSize = new GSize(37, 32);
		icon.iconAnchor = new GPoint(16, 32);
		icon.infoWindowAnchor  = new GPoint(16, 32);
		marker = new GMarker(new GLatLng(lat, lng), {"title":title, "icon":icon});
	} else {
		marker = new GMarker(new GLatLng(lat, lng), {"title":title});
	}
    if(html != ''){
      //GEvent.addListener(marker, 'click', function() {
      GEvent.addListener(marker, 'mouseover', function() {
          var markerHTML = html;
          marker.openInfoWindowHtml(markerHTML);
      });
    }
	return marker;
}

/**
 *
 **/
function find_street(item){
	$.ajax({
		type:"get",
		url: "<?php echo base_url(); ?>calles/nombre/"+item,
		//data:{'item': item},
		success: function(rsp) {
		  var marker = rsp.documentElement;
		  var name = marker.getAttribute('name');
			if (name == item){
			  var lat = marker.getAttribute('lat');
			  var lng = marker.getAttribute('lng');
			  name = item.replace(/-/g, ' ');
			  if ((lat == "") || (lng == "")){
				text = "<p class='comment'>Podes ayudarnos a encontrar la Calle <strong>"+name+"</strong> a traves de: </p>";
				create_dialog(text);
			  }else{				
				var markermap = new GMarker(new GLatLng(lat, lng), {"title":name});
				map.addOverlay(markermap);
				map.panTo(new GLatLng(lat, lng));
				//add the points if exists
				var points = marker.getElementsByTagName('point');
				if(points.length > 0){
					var source, dest, distance;
					var polyPoints = new Array();
					for(var j=0; j<points.length; j++){
						lat = points[j].getAttribute('lat');
						lng = points[j].getAttribute('lng');			
						polyPoints.push(new GLatLng(lat, lng));
						
						//calculations
						if(j>0){
							source = new LatLon(parseFloat(polyPoints[j-1].lat()),parseFloat(polyPoints[j-1].lng()));
							dest = new LatLon(parseFloat(polyPoints[j].lat()),parseFloat(polyPoints[j].lng()));
							distance += source.distanceTo(dest, 2) * 1000;							
						}else{
							distance = 0;
						}
					}
					var polyline = new GPolyline(polyPoints,"#BF0A2B", 9);
					map.addOverlay(polyline);
					
					var scale = "m";
					var txt = '<div id="distance" align="center" class="centered ui-state-highlight"><p>Longitud aproximada de <strong>'+name+'</strong>: '+distance+' '+scale+'.</p></div>';
					$('#distance').replaceWith(txt).fadeIn(8000);
					$('#distance').mouseout(function(){$(this).fadeOut(5000);});					
				} else{
					$("#distance").fadeOut("fast");
				}
			  }
			  return;
			}
		}
	});
}

function locate(type, item) {
	item = item.replace(/_/g, '-');
	find(type, item);  	
	$("#map").dialog('open');
}

function find(type, item) {
	  $.getJSON("<?php echo base_url(); ?>"+type+"/name/"+item, function(data){
		    var clean_name = data.name.replace(/-/g, ' ');		    
		    var html = write_html(type,data.name,clean_name, data.img, data.address+' - '+data.city, data.description);
		    var marker = createMarker(data.lat, data.lng, html, data.icon, clean_name);
		    map.addOverlay(marker);
			map.panTo(new GLatLng(data.lat, data.lng));	
			marker.openInfoWindowHtml(html);
			show_distance(data.name, data.lat, data.lng);
		    /*
		    //add the marker to the bounds
			var bounds = new GLatLngBounds();
		    bounds.extend(marker.getPoint());
		    //set the center using BOUNDS
		    var center = bounds.getCenter();
		    var zoom = map.getBoundsZoomLevel(bounds);
		    map.setCenter(center,zoom);
		    */			
	  });
}

function find_all(type){
	  $.getJSON("<?php echo base_url(); ?>"+type+"/all/", function(data){
		    var bounds = new GLatLngBounds();
		    $.each(data, function(i, val) {
		      var clean_name = val.name.replace(/-/g, ' ');		    
		      var html = write_html(type,val.name,clean_name, val.img, val.address+' - '+val.city, val.description);
		      var marker = createMarker(val.lat, val.lng, html, val.icon, clean_name);
		      map.addOverlay(marker);
		      //add the marker to the bounds
		      bounds.extend(marker.getPoint());
		    });
		    //set the center using BOUNDS
		    var center = bounds.getCenter();
		    var zoom = map.getBoundsZoomLevel(bounds);
		    map.setCenter(center,zoom);
		  });	
}

/**
 * Locate all open pharmacies
 */
function deturno(){
	  $.getJSON("<?php echo base_url(); ?>farmacias/deturno/", function(data){
		    var bounds = new GLatLngBounds();
		    $.each(data, function(i, val) {
		      var clean_name = val.name.replace(/-/g, ' ');		    
		      var html = write_html('farmacias',val.name,clean_name, val.img, val.address+' - '+val.city, val.description);
		      var marker = createMarker(val.lat, val.lng, html, val.icon, clean_name);
		      map.addOverlay(marker);
		      //add the marker to the bounds
		      bounds.extend(marker.getPoint());
		    });
		    //set the center using BOUNDS
		    var center = bounds.getCenter();
		    var zoom = map.getBoundsZoomLevel(bounds);
		    map.setCenter(center,zoom);
		  });	
}

/**
* Wrapper function to build the map info
**/
function write_html(cat,item, name, img, add, desc){
  img = (img!="")?"<figure><img alt='"+name+"' class='lheader map_img' style='height: 100px; width: 75px' src='"+img+"'/></figure>":"";
	var html="<div class='map_info' align='center'>"+
			  	"<div class='map_title'>"+name+
				  //"<h3>"+name+"</h3>"+
			  	"</div>"+	
				"<div>"+
				 	img+"<p class='comment'>"+add+"</p>"+//desc+
                	"<p><a class='comment' href='<?php echo base_url(); ?>"+cat+"/nombre/"+item+"' target='_new'>Mas informacion...</a></p>"+
				"</div>"+
				'<div style="margin-top:3px"><iframe src="http://www.facebook.com/plugins/like.php?href=www.conocepunta.com.ar/'+cat+'/nombre/'+item+'&amp;layout=button_count&amp;show-faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;locale=es_LA" frameborder="0" scrolling="no" style="vertical-align: middle; border: medium none; overflow: hidden; width: 100px; height: 21px;" allowtransparency="true"></iframe></div>'+
				//'<div><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="conocepunta">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"><\/script></div>'+
			 "</div>";
	return html;
}

/**
 * Geolocation
 **/
function show_me(){
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(position){
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;
            var html = "<p>Gracias por la buena onda!</p>";
            var iconImage = "";
            var name ="Me encuentro aqui";
            var markermap = createMarker(lat, lng, html, iconImage, name);
            map.addOverlay(markermap);
            map.panTo(new GLatLng(lat, lng));
            markermap.openInfoWindowHtml(html);
        });
    } else{
        var text = "<p class='comment'>Tu navegador no soporta esta funcionalidad.</p><p class='comment'>Actualizalo!!!</p>";
        create_dialog(text);
    }
}

/**
 * Show estimate distance from item to central square
 * @param item: Name of the source place
 * @param slat: latitude of item
 * @param slng: longitude of item
 **/
function show_distance(item, slat, slng){
    var source = new LatLon(parseFloat(slat),parseFloat(slng));
    var dest = new LatLon(parseFloat(-38.880430824937385),parseFloat(-62.0748777688641));   //distance to central park
    var distance = source.distanceTo(dest, 2);    
    //in hours
    var walk_time = distance / 3.5;
    var wht = Math.floor(walk_time);
    var wht_text = (wht > 0) ? (wht+" hr") : "";
    var wmt = Math.floor(((walk_time - wht) * 60));
    //var wst = Math.floor((((walk_time - wht) * 60) - wmt) * 60);

    var car_time = distance / 10;
    var cht = Math.floor(car_time);
    var cht_text = (cht > 0) ? (cht+" hr") : "";    
    var cmt = Math.floor(((car_time - cht) * 60));
    //var cst = Math.floor((((car_time - cht) * 60) - cmt) * 60);
	
    var scale = "km";
    if(distance < 1){
        distance = distance * 1000;
        scale = "m";
    }
    var txt = '<div id="distance" align="center" class="centered ui-state-highlight"><p>Distancia desde <strong>'+item+'</strong> hasta la <strong>Plaza Belgrano</strong>: '+distance+' '+scale+'.</p>'+
              '<p><strong>Caminando</strong>: '+wht_text+' '+wmt+' min.</p><p>En <strong>vehiculo</strong>: '+cht_text+' '+cmt+' min.</p>'+
              '<h4>Todos los valores son aproximados.</h4></div>';
    $('#distance').replaceWith(txt);
    $('#distance').fadeIn(8000);
    $('#distance').show(15000);
    $('#distance').mouseout(function(){$(this).fadeOut(5000);});

    return txt;
}

/**
 *Get points of Centro Club Marathon
 **/
 /*
function load_marathon(){
	$.ajax({
		type:"get",
		url:"<?php echo base_url(); ?>deporte/get_marathon",
        //url:"points.xml",
		//data:{'item': item},
		success: function(rsp) {
		 var markers = rsp.getElementsByTagName('marker');
		  var cant = markers.length;
          var source, dest, distance, markermap;
          var polyPoints = new Array();
		  for (var i = 0; i < cant; i++) {
			var lat = markers[i].getAttribute('lat');
            var lng = markers[i].getAttribute('lng');
            var iconImage = markers[i].getAttribute('icon');
            polyPoints.push(new GLatLng(lat, lng));
            //calculations
            if(i>0){
                source = new LatLon(parseFloat(polyPoints[i-1].lat()),parseFloat(polyPoints[i-1].lng()));
                dest = new LatLon(parseFloat(polyPoints[i].lat()),parseFloat(polyPoints[i].lng()));
                distance += source.distanceTo(dest, 2) * 1000;
                markermap = createMarker(lat, lng, '', iconImage, distance + " metros");
               //markermap = new GMarker(new GLatLng(lat, lng), {"title":distance + " metros", "icon":""});
                map.addOverlay(markermap);
            }else{
                distance = 0;                
            }            
          }
          var polyline = new GPolyline(polyPoints,"#FF8000", 8, 0.7);
          map.addOverlay(polyline);
		}
	});
}
*/

/**
* Show ATMs
**/
function get_atms(){
  $.getJSON("<?php echo base_url(); ?>interes/cajeros/", function(data){
    var bounds = new GLatLngBounds();
    $.each(data, function(i, val) {
      var html = write_html("interes",val.name,"Cajero", val.img, val.add, val.desc);
      var marker = createMarker(val.lat, val.lng, html, val.icon, val.name);
      map.addOverlay(marker);
      //add the marker to the bounds
      bounds.extend(marker.getPoint());
    });
    //set the center using BOUNDS
    var center = bounds.getCenter();
    var zoom = map.getBoundsZoomLevel(bounds);
    map.setCenter(center,zoom);
  });
}

/**
* Show hotplaces according to past events
**/
$(function(){
  $.getJSON("<?php echo base_url(); ?>estadisticas/get_stats/", function(data){
    $.each(data, function(i, val) {
      var content;
      if(val > 0.1){
        content = "<span class='high_rate rate rheader'></span>";
      }else if(val >= 0.025){
        content = "<span class='mid_rate rate rheader'></span>";
      }else{
        content = "<span class='low_rate rate rheader'></span>";
      }
      $("#" + i + " > .title:first").append(content);
      $("#" + i + ".listOpt").append(content);
    });
  });
});

</script>